//
//  SportViewController.m
//  FitTime
//
//  Created by 赵建平 on 16/3/30.
//  Copyright © 2016年 赵建平. All rights reserved.
//

#import "SportViewController.h"
#import "SportView.h"
#import "SportSeletButtonCVCell.h"
#import "MapViewController.h"
#import "RunInViewController.h"
#import "SportData.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapNaviKit/AMapNaviKit.h>
#import <CoreMotion/CoreMotion.h>
#import "WeatherView.h"
#import "GiFHUD.h"



#define GRAMMAR_TYPE_ABNF    @"abnf"

@interface SportViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, AMapSearchDelegate, MAMapViewDelegate>

@property (nonatomic, strong) UIButton *selectButton;
@property (nonatomic, strong) SportView *popView;
@property (nonatomic, strong) SportView *downView;
@property (nonatomic, assign) BOOL popViewIsHiden;
@property (nonatomic, strong) NSArray *datasource;
@property (nonatomic, strong) NSArray *imageArray;
@property (nonatomic, strong) NSArray *colorArray;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *startTitleArray;
@property (nonatomic, strong) UIButton *startButton;
@property (nonatomic, strong) UILabel *mileageLabel;  // 总里程label
@property (nonatomic, strong) UILabel *showMileageLabel;//显示总里程数据
@property (nonatomic, strong) UILabel *timeLabel; // 总时间label
@property (nonatomic, strong) UILabel *showTimeLabel; //显示总时间数据
@property (nonatomic, strong) UILabel *countLabel; // 总次数label
@property (nonatomic, strong) UILabel *showCountLabel; //显示总次数数据
@property (nonatomic, strong) NSString *startSportType; // 开始按钮运动类型

// CoreData
@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, strong) NSMutableArray *coreDataArray;
@property (nonatomic, assign) CGFloat sumMileage;
@property (nonatomic, assign) CGFloat sumTime;
@property (nonatomic, assign) NSInteger sumCount;

// 天气搜索
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) CLLocation *currentLocation;
@property (nonatomic, strong) NSString *currentCity;
@property (nonatomic, strong) WeatherView *weatherView;

// 语音shibie
@property (nonatomic, strong) NSMutableString *result;
@property (nonatomic, strong) IFlyDataUploader *uploader;


@end

@implementation SportViewController

static NSString * _cloudGrammerid =nil;//在线语法grammerID

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationBar.translucent = YES;
    [self initIflyRecognizerView];
    
    [self selectCoreData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [_iflyRecognizerView cancel]; //取消识别
    [_iflyRecognizerView setDelegate:nil];
    [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.coreDataManager = [CoreDataManager shareCoreDataManager];
    self.coreDataArray = [NSMutableArray arrayWithCapacity:0];
    
    [self iniitAttributeAndMethod];
    
}


- (void)iniitAttributeAndMethod
{
    [MAMapServices sharedServices].apiKey = @"612caf2047ce93b6a9b106c2cd1bed7a";
    [AMapSearchServices sharedServices].apiKey = @"612caf2047ce93b6a9b106c2cd1bed7a";
    self.datasource = @[@"runout-2.png", @"runin-2.png", @"walk-2.png", @"qixing-2.png", @"huaxue-2.png", @"huabing-2.png"];
    self.imageArray = @[@"runout.png", @"runin.png", @"walk.png", @"qixing.png", @"huaxue.png", @"huabing.png"];
    self.titleArray = @[@"户外跑步", @"室内跑步", @"走路", @"骑行", @"滑雪", @"滑冰"];
    self.startTitleArray = @[@"跑步", @"室内跑步", @"走路", @"骑行", @"滑雪", @"滑冰"];
    self.startSportType = @"跑步";
    

    [self createBackgroundImage];
    [self createMapView];
    [self createSelectButton];
    [self createWeather];
    [self createPopView];
    [self createCollectionView];
    [self createStartButton];
    [self createMileageLabel];
    [self createTimeLabel];
    [self createCountLabel];
    [self initUploader];
    [self buildGrammer];
}

- (void)createBackgroundImage {
    
    UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    backgroundImageView.image = [UIImage imageNamed:@"background.jpg"];
    [self.view addSubview:backgroundImageView];
    
    //  语音按钮
    UIButton *speechButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    speechButton.frame = CGRectMake(SCREENWIDTH / 2 - 30 * SCALEWIDTH , CGRectGetHeight(self.view.bounds) - 120 * SCALEHEIGHT, 60 * SCALEHEIGHT, 60 * SCALEHEIGHT);
    speechButton.center = CGPointMake(self.view.center.x, speechButton.center.y);
    speechButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    speechButton.backgroundColor = [UIColor clearColor];
    [speechButton setImage:[UIImage imageNamed:@"speech"] forState:UIControlStateNormal];
    
    [speechButton addTarget:self action:@selector(speechButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:speechButton];
    
    
}

- (void)initSearchWeather {
    
    //构造AMapWeatherSearchRequest对象，配置查询参数
    AMapWeatherSearchRequest *request = [[AMapWeatherSearchRequest alloc] init];
    request.city = self.currentCity;
    request.type = AMapWeatherTypeLive; //AMapWeatherTypeLive为实时天气；AMapWeatherTypeForecase为预报天气
    
    //发起行政区划查询
    [_search AMapWeatherSearch:request];
}

#pragma mark - 语音听写
- (void)initIflyRecognizerView
{
    //单例模式，UI的实例
    if (_iflyRecognizerView == nil) {
        //UI显示剧中
    _iflyRecognizerView = [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
    [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    //  识别领域  普通
    [_iflyRecognizerView setParameter: @"iat" forKey: [IFlySpeechConstant IFLY_DOMAIN]];
    }
    _iflyRecognizerView.delegate = self;
    //设置音频来源为麦克风
    [_iflyRecognizerView setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
    //  前端点检测时间
    [_iflyRecognizerView setParameter: @"6000" forKey: [IFlySpeechConstant VAD_BOS]];
    //  后端点检测时间
    [_iflyRecognizerView setParameter: @"700" forKey: [IFlySpeechConstant VAD_EOS]];
    //  采样频率
    [_iflyRecognizerView setParameter: @"8000" forKey: [IFlySpeechConstant SAMPLE_RATE]];
    //  设置返回结果中包含标点符号
    [_iflyRecognizerView setParameter: @"1" forKey: [IFlySpeechConstant ASR_PTT]];
    //  返回结构类型
    [_iflyRecognizerView setParameter: @"plain" forKey: [IFlySpeechConstant RESULT_TYPE]];
    //asr_audio_path保存录音文件名，如不再需要，设置value为nil表示取消，默认目录是documents
    [_iflyRecognizerView setParameter:@"asrview.pcm " forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    

}
/**
 设置识别参数
 ****/
-(void)initRecognizer
{
    //语法识别实例
    
    //单例模式，无UI的实例
    if (_iFlySpeechRecognizer == nil) {
        _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
    }
    _iFlySpeechRecognizer.delegate = self;
    //设置听写模式
    [_iFlySpeechRecognizer setParameter:@"asr" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    //设置听写结果格式为json
    [_iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];
    //设置音频来源为麦克风
    [_iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
    //  前端点检测时间
    [_iFlySpeechRecognizer setParameter: @"6000" forKey: [IFlySpeechConstant VAD_BOS]];
    //  后端点检测时间
    [_iFlySpeechRecognizer setParameter: @"700" forKey: [IFlySpeechConstant VAD_EOS]];
    //  采样频率
    [_iFlySpeechRecognizer setParameter: @"8000" forKey: [IFlySpeechConstant SAMPLE_RATE]];
    //  设置返回结果中包含标点符号
    [_iFlySpeechRecognizer setParameter: @"1" forKey: [IFlySpeechConstant ASR_PTT]];
    //  返回结构类型
    [_iFlySpeechRecognizer setParameter: @"plain" forKey: [IFlySpeechConstant RESULT_TYPE]];
    //asr_audio_path保存录音文件名，如不再需要，设置value为nil表示取消，默认目录是documents
    [_iFlySpeechRecognizer setParameter:@"asrview.pcm " forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    
}

#pragma mark - 上传运动库  语音识别
- (void)initUploader
{
    _uploader = [[IFlyDataUploader alloc] init];
    IFlyUserWords *iflyUserWords = [[IFlyUserWords alloc] initWithJson:USERWORDS];
    // 设置参数
    [_uploader setParameter:@"iat" forKey:[IFlySpeechConstant SUBJECT]];
    [_uploader setParameter:@"contant" forKey:[IFlySpeechConstant DATA_TYPE]];
    // 上传词表
    [_uploader uploadDataWithCompletionHandler:^(NSString * grammerID, IFlySpeechError *error)
        {
    } name:NAME data:[iflyUserWords toString]];
    
}

- (void)initShowData
{
    self.showMileageLabel.text = [NSString stringWithFormat:@"%.2f", self.sumMileage / 1000.0];
    self.showMileageLabel.font = [UIFont systemFontOfSize:70 * SCALEWIDTH];
    self.showMileageLabel.textColor = [UIColor whiteColor];
    
    // 时间
    NSString *string = [NSString stringWithFormat:@"%.2f小时", self.sumTime];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range = [string rangeOfString:@"小时"];
    [attributedString setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14 * SCALEWIDTH]} range:range];
    self.showTimeLabel.font = [UIFont systemFontOfSize:30 * SCALEWIDTH];
    self.showTimeLabel.attributedText = attributedString;
    self.showTimeLabel.textColor = [UIColor whiteColor];
    
    //  次数
    NSString *str = [NSString stringWithFormat:@"%ld", self.sumCount];
    NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] initWithString:str];
    NSRange rang = [str rangeOfString:@"次"];
    [attributed setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14 * SCALEWIDTH]} range:rang];
    self.showCountLabel.font = [UIFont systemFontOfSize:30 * SCALEWIDTH];
    self.showCountLabel.attributedText = attributed;
    self.showCountLabel.textColor = [UIColor whiteColor];
    
}

#pragma mark - 构建语法
- (void)buildGrammer
{
    NSString *grammarContext = nil;
    NSString *appPath = [[NSBundle mainBundle] resourcePath];
    //设置字符编码
    [_iFlySpeechRecognizer setParameter:@"utf-8" forKey:[IFlySpeechConstant TEXT_ENCODING]];
    [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant SUBJECT]];
    
    //  读取内容
    NSString *bnfFilePath = [[NSString alloc] initWithFormat:@"%@/bnf/grammar_sample.abnf",appPath];
    grammarContext = [self readFile:bnfFilePath];
    //  开始构建
    //开始构建
    [_iFlySpeechRecognizer buildGrammarCompletionHandler:^(NSString * grammerID, IFlySpeechError *error){
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (![error errorCode]) {
                
                NSLog(@"errorCode=%d",[error errorCode]);
                
                
            }
            else {
                NSLog(@"上传失败");
            }
            //设置grammarid
            [_iFlySpeechRecognizer setParameter:_cloudGrammerid forKey:[IFlySpeechConstant CLOUD_GRAMMAR]];
        });
        
    }grammarType:self.grammarType grammarContent:grammarContext];
    
}
/**
 文件读取
 *****/
-(NSString *)readFile:(NSString *)filePath
{
    NSData *reader = [NSData dataWithContentsOfFile:filePath];
    return [[NSString alloc] initWithData:reader encoding:NSUTF8StringEncoding];
}

- (void)createRego {
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    //构造AMapReGeocodeSearchRequest对象
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    regeo.location = [AMapGeoPoint locationWithLatitude:self.currentLocation.coordinate.latitude     longitude:self.currentLocation.coordinate.longitude];
    regeo.radius = 10000;
    regeo.requireExtension = YES;
    //发起逆地理编码
    [_search AMapReGoecodeSearch: regeo];
}

- (void)createMapView {
    self.mapView = [[MAMapView alloc] init];
    self.mapView.delegate = self;
    self.mapView.showsUserLocation = YES;
    [self.mapView setUserTrackingMode:MAUserTrackingModeNone animated:YES];
    [self.view addSubview:self.mapView];
    
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    
    self.currentLocation = userLocation.location;
    [self createRego];
    self.mapView.delegate = nil;
    
}
//  逆地理编码
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response {
    
    self.currentCity = response.regeocode.addressComponent.city;
    if (response.regeocode.addressComponent.city.length == 0) {
        self.currentCity = response.regeocode.addressComponent.province;
    }
    
    [self initSearchWeather];

}

- (void)onWeatherSearchDone:(AMapWeatherSearchRequest *)request response:(AMapWeatherSearchResponse *)response {
    //如果是实时天气
    if(request.type == AMapWeatherTypeLive)
    {
        if(response.lives.count == 0)
        {
            return;
        }
        for (AMapLocalWeatherLive *live in response.lives) {
           if ([live.weather isEqualToString:@"多云"]) {
                self.weatherView.weatherImageView.image = [UIImage imageNamed:@"duoyun.png"];
            } else if ([live.weather isEqualToString:@"晴"]) {
                self.weatherView.weatherImageView.image = [UIImage imageNamed:@"qing.png"];
            } else if ([live.weather isEqualToString:@"小雨"]) {
                self.weatherView.weatherImageView.image = [UIImage imageNamed:@"xiaoyu.png"];
            } else if ([live.weather isEqualToString:@"大雨"]) {
                self.weatherView.weatherImageView.image = [UIImage imageNamed:@"dayu.png"];
            } else if ([live.weather isEqualToString:@"阵雨"]) {
                self.weatherView.weatherImageView.image = [UIImage imageNamed:@"zhenyu.png"];
            } else if ([live.weather isEqualToString:@"阴"]) {
                self.weatherView.weatherImageView.image = [UIImage imageNamed:@"yin.png"];
            } else {
                self.weatherView.weatherImageView.image = [UIImage imageNamed:@"yin.png"];
            }
            
            self.weatherView.temperatureLabel.text = [NSString stringWithFormat:@"%@°C", live.temperature];
            self.weatherView.weatherLabel.text = live.weather;
            self.weatherView.cityLabel.text = live.city;
            self.weatherView.localImageView.image = [UIImage imageNamed:@"dingwei.png"];
            self.weatherView.humidityImageView.image = [UIImage imageNamed:@"shidu.png"];
            self.weatherView.humidityLabel.text = [NSString stringWithFormat:@"%@%%", live.humidity];
            self.weatherView.windPowerImageView.image = [UIImage imageNamed:@"fengli.png"];
            self.weatherView.windPowerLabel.text = [NSString stringWithFormat:@"%@风%@级", live.windDirection, live.windPower];                        
        }
    }
    //如果是预报天气
    else
    {
        if(response.forecasts.count == 0)
        {
            return;
        }
        for (AMapLocalWeatherForecast *forecast in response.forecasts) {
           
        }
    }
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error {
    NSLog(@"%@", error);
}

#pragma mark - CoreData 
- (void)selectCoreData {
    
    self.sumTime = 0;
    self.sumMileage = 0;
    self.sumCount = 0;
    
    //  查找所有运动数据
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"SportData" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@", error);
    } else {
        NSLog(@"++++++++%@", [self.coreDataManager applicationDocumentsDirectory]);
        self.coreDataArray = [NSMutableArray arrayWithArray:fetchedObjects] ;
        for (SportData *data in self.coreDataArray) {
            self.sumMileage += data.sumMileage.floatValue;
            self.sumTime += data.sumTime.floatValue;
            self.sumCount += data.sumCount.intValue;
        }
    }
    [self initShowData];
}

#pragma mark - 右上角选择按钮
- (void)createSelectButton {
    
    self.selectButton = [UIButton buttonWithTitle:nil frame:CGRectMake(5, StatusBarHeight, 32 * SCALEWIDTH, 32 * SCALEWIDTH) target:self action:@selector(selectButtonAction)];
    [self.selectButton setBackgroundImage:[UIImage imageNamed:@"runout"] forState:UIControlStateNormal];
    [self.view addSubview:self.selectButton];
}

#pragma mark - 天气
- (void)createWeather {
    
    self.weatherView = [WeatherView new];
    [self.view addSubview:self.weatherView];
    [self.weatherView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.view.mas_top).offset(20 * SCALEHEIGHT);
        make.left.equalTo(self.view.mas_left).offset(50 * SCALEWIDTH);
        make.right.equalTo(self.view.mas_right).offset(-50 * SCALEWIDTH);
        make.height.equalTo(@(120 * SCALEHEIGHT));
    }];
    self.weatherView.layer.masksToBounds = YES;
    self.weatherView.layer.cornerRadius = 10 * SCALEWIDTH;
    
}

#pragma mark - 总里程label
- (void)createMileageLabel {
    
    self.mileageLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.view addSubview:self.mileageLabel];
    [self.mileageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY).offset(-100 * SCALEHEIGHT);
        make.height.equalTo(@(20 * SCALEHEIGHT));
    }];
    self.mileageLabel.text = @"运动总里程(公里)";
    self.mileageLabel.textColor = [UIColor whiteColor];
    
    self.showMileageLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.view addSubview:self.showMileageLabel];
    [self.showMileageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.equalTo(self.mileageLabel.mas_bottom).offset(-20 * SCALEHEIGHT);
        make.height.equalTo(@(100 * SCALEHEIGHT));

    }];
    
   
    
}

#pragma mark - 总时间label
- (void)createTimeLabel {
    
    self.timeLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.view addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX).offset(-100 * SCALEWIDTH);
        make.centerY.equalTo(self.view.mas_centerY);
        make.height.equalTo(@(20 * SCALEHEIGHT));
    }];
    self.timeLabel.text = @"累计用时";
    self.timeLabel.textColor = [UIColor whiteColor];
    
    self.showTimeLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.view addSubview:self.showTimeLabel];
    [self.showTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.timeLabel.mas_centerX);
        make.bottom.equalTo(self.timeLabel.mas_bottom).offset(-20 * SCALEHEIGHT);
        make.height.equalTo(@(50 * SCALEHEIGHT));
        
    }];
   
    
    
}
#pragma mark - 总次数label
- (void)createCountLabel {
    
    self.countLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.view addSubview:self.countLabel];
    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX).offset(100 * SCALEWIDTH);
        make.centerY.equalTo(self.view.mas_centerY);
        make.height.equalTo(@(20 * SCALEHEIGHT));
    }];
    self.countLabel.text = @"运动次数";
    self.countLabel.textColor = [UIColor whiteColor];
    
    self.showCountLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor clearColor] alignment:NSTextAlignmentCenter];
    [self.view addSubview:self.showCountLabel];
    [self.showCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.countLabel.mas_centerX);
        make.bottom.equalTo(self.countLabel.mas_bottom).offset(-20 * SCALEHEIGHT);
        make.height.equalTo(@(50 * SCALEHEIGHT));
        
    }];
    
    
    
}

#pragma mark - 开始运动按钮
- (void)createStartButton {
    
    if (!self.startButton) {
        
        self.startButton = [UIButton buttonWithTitle:@"开始跑步" frame:CGRectZero target:self action:@selector(startButtonAction)];
        [self.view addSubview:self.startButton];
        
        self.startButton.layer.borderWidth = 3;
        self.startButton.layer.borderColor = [UIColor whiteColor].CGColor;
        
        [self.startButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.centerX.equalTo(self.view.mas_centerX);
            make.centerY.equalTo(self.view.mas_centerY).mas_equalTo(@(160 * SCALEHEIGHT));
            make.width.equalTo(@(50 * SCALEWIDTH));
            make.height.equalTo(@(50 * SCALEWIDTH));
        }];
        self.startButton.layer.masksToBounds = YES;
        self.startButton.layer.cornerRadius = 25 * SCALEWIDTH;
        self.startButton.titleLabel.numberOfLines= 2;
        self.startButton.titleLabel.font = [UIFont systemFontOfSize:18 * SCALEWIDTH];
        [self.startButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    
}
#pragma mark - Targate Action
- (void)startButtonAction {
    
    //  室内跑步
    if ([self.startSportType isEqualToString:@"室内跑步"]) {
        RunInViewController *runInVC = [[RunInViewController alloc] init];
        
        __weak SportViewController *sportVC = self;
        
        runInVC.distanceBlock = ^(NSString *distance, CGFloat sumTime) {
            
            sportVC.showMileageLabel.text = distance;
            
            NSString *string = [NSString stringWithFormat:@"%.2f小时", sumTime / 3600.0];
            NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
            NSRange range = [string rangeOfString:@"小时"];
            [attributedString setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14 * SCALEWIDTH]} range:range];
            sportVC.showTimeLabel.attributedText = attributedString;
        };
        [self.navigationController pushViewController:runInVC animated:YES];
        
    } else {
    
    MapViewController *mapView = [[MapViewController alloc] init];
    mapView.sportType = self.startSportType;
    __weak SportViewController *sportVC = self;
        
    mapView.distanceBlock = ^(NSString *distance, CGFloat sumTime, NSInteger count) {
        //  每次返回数据加 历史数据
        CGFloat sumDistance = sportVC.sumMileage / 1000.0 + distance.floatValue;
        sportVC.showMileageLabel.text = [NSString stringWithFormat:@"%.2f", sumDistance];
        
        NSString *string = [NSString stringWithFormat:@"%.2f小时", sumTime/ 3600.0 + sportVC.sumTime];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
        NSRange range = [string rangeOfString:@"小时"];
        [attributedString setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14 * SCALEWIDTH]} range:range];
        sportVC.showTimeLabel.attributedText = attributedString;
        
        sportVC.showCountLabel.text = [NSString stringWithFormat:@"%ld", sportVC.sumCount + count];
    };
    
    [self.navigationController pushViewController:mapView animated:YES];
    
  }
}


- (void)selectButtonAction {
    
    [UIView animateWithDuration:0.5f animations:^{
        self.popView.frame = CGRectMake(0, StatusBarHeight, SCREENWIDTH, SCREENHEIGHT - StatusBarHeight);
       
    }];
}

- (void)speechButtonAction
{
//    [self initIflyRecognizerView];
    //启动识别服务
    [_iflyRecognizerView start];
}

#pragma mark - 选择按钮------弹出视图
- (void)createPopView {
    
    self.popView = [[SportView alloc] initWithFrame:CGRectMake(0,SCREENHEIGHT, SCREENWIDTH, SCREENHEIGHT - StatusBarHeight)];
    self.popView.backgroundColor = [UIColor clearColor];
    [[UIApplication sharedApplication].keyWindow addSubview:self.popView];
    
    // 上方view
    SportView *topView = [[SportView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, self.popView.frame.size.height / 2)];
    topView.backgroundColor = [UIColor clearColor];
    [self.popView addSubview:topView];
    //  手势控制弹出和收起
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [topView addGestureRecognizer:tap];
    
    //  下方view
    self.downView = [[SportView alloc] initWithFrame:CGRectMake(0, self.popView.frame.size.height / 2, SCREENWIDTH, self.popView.frame.size.height / 2)];
    self.downView.backgroundColor = [UIColor whiteColor];
    [self.popView addSubview:self.downView];
    //  downView上布局
    UILabel *sportLabel = [UILabel labelWithFrame:CGRectZero color:[UIColor orangeColor] alignment:NSTextAlignmentCenter];
    [self.downView addSubview:sportLabel];
    [sportLabel mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerX.equalTo(self.downView.mas_centerX);
        make.top.equalTo(self.downView);
        make.left.equalTo(self.downView.mas_left);
        make.height.equalTo(@(50 * SCALEHEIGHT));
    }];
    sportLabel.text = @"选择你的运动类型";
    sportLabel.font = [UIFont systemFontOfSize:20 * SCALEWIDTH];
    //  关闭按钮
    UIButton *closeButton = [UIButton buttonWithTitle:@"guanbi.png" frame:CGRectZero target:self action:@selector(closeButtonAction)];
    [sportLabel addSubview:closeButton];
    closeButton.backgroundColor = [UIColor redColor];
    [sportLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(sportLabel.mas_centerY);
        make.right.equalTo(sportLabel.mas_right);
        make.width.equalTo(@(32 * SCALEWIDTH));
        make.height.equalTo(@(32 * SCALEWIDTH));
        
    }];
    
}

- (void)closeButtonAction {
    [UIView animateWithDuration:0.5f animations:^{
        self.popView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, SCREENHEIGHT - StatusBarHeight);
    }];
}

#pragma mark - 手势方法
- (void)tapAction:(UITapGestureRecognizer *)tap {
    
    [UIView animateWithDuration:0.5f animations:^{
        self.popView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, SCREENHEIGHT - StatusBarHeight);
    }];
}

- (void)createCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(SCREENWIDTH / 3,(self.downView.frame.size.height - 50) / 2);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 50, SCREENWIDTH, self.downView.frame.size.height - 50 * SCALEHEIGHT) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.downView addSubview:self.collectionView];
    [self.collectionView registerClass:[SportSeletButtonCVCell class] forCellWithReuseIdentifier:@"SportSeletButtonCVCell"];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 6;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SportSeletButtonCVCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SportSeletButtonCVCell" forIndexPath:indexPath];
    cell.jpImageView.image = [UIImage imageNamed:self.imageArray[indexPath.item]];
    
    cell.titleLabel.text = self.titleArray[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //  开始按钮改变
    if (indexPath.item == 1) {
    [self.startButton setTitle:@"开始跑步" forState:UIControlStateNormal];
    } else {
    [self.startButton setTitle:[NSString stringWithFormat:@"开始%@", self.startTitleArray[indexPath.row]] forState:UIControlStateNormal];
    }
    self.startSportType = self.startTitleArray[indexPath.row];
    // 总里程 改变
    SportSeletButtonCVCell *cell = (SportSeletButtonCVCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
   
    cell.jpImageView.image = [UIImage imageNamed:self.datasource[indexPath.item]];
    // 替换选择按钮视图
    [self.selectButton setBackgroundImage:[UIImage imageNamed:self.imageArray[indexPath.item]] forState:UIControlStateNormal];
    
    // 收回视图
    [UIView animateWithDuration:0.5f animations:^{
        self.popView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, SCREENHEIGHT - StatusBarHeight);
    }];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SportSeletButtonCVCell *cell = (SportSeletButtonCVCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    
    cell.jpImageView.image = [UIImage imageNamed:self.imageArray[indexPath.item]];
    
}
#pragma mark - IFlyRecognizerViewDelegate
- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast
{
    self.result = [[NSMutableString alloc] init];
    NSDictionary *dictionary = [resultArray firstObject];
    
    for (NSString *key in dictionary) {
        [_result appendFormat:@"%@", key];
    }
    
    if ([_result isEqualToString:@"我要跑步"] || [_result isEqualToString:@"我要室内跑步"] || [_result isEqualToString:@"我要走路"] || [_result isEqualToString:@"我要骑行"] || [_result isEqualToString:@"我要滑雪"] || [_result isEqualToString:@"我要滑冰"] ) {
        [_result deleteCharactersInRange:NSMakeRange(0, 2)];
        self.startSportType = _result;
        [self startButtonAction];
    } else if ([_result isEqualToString:@"跑步"] || [_result isEqualToString:@"室内跑步"] || [_result isEqualToString:@"走路"] || [_result isEqualToString:@"骑行"] || [_result isEqualToString:@"滑雪"] || [_result isEqualToString:@"滑冰"]) {
        self.startSportType = _result;
        [self startButtonAction];
    } else if ([_result hasSuffix:@"天气"]) {
    [_result deleteCharactersInRange:NSMakeRange(_result.length - 2, 2)];
        self.currentCity = _result;
        [self initSearchWeather];
    } else if ([_result hasSuffix:@"天气预报"]) {
        [_result deleteCharactersInRange:NSMakeRange(_result.length - 4, 4)];
        self.currentCity = _result;
        [self initSearchWeather];
    } else if ([_result hasSuffix:@"毛毛"] || [_result hasSuffix:@"刘鹏程"]){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"高能预警" message:@"您的命令不正确！手机将在5秒后爆炸！！！！" preferredStyle:UIAlertControllerStyleAlert];
        alertController.view.backgroundColor = [UIColor redColor];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"扔掉电话" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];
        
        [alertController addAction:alertAction];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if ([_result hasSuffix:@"老王"] || [_result hasSuffix:@"王建南"] || [_result hasSuffix:@"南哥"] || [_result hasSuffix:@"楠哥楠哥"]){
        [GiFHUD setGifWithImageName:@"laowang.gif"];
        [GiFHUD show];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"ShowTiming" message:@"老王表演时刻！！！！" preferredStyle:UIAlertControllerStyleActionSheet];
        alertController.view.backgroundColor = [UIColor redColor];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"不看了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [GiFHUD dismiss];
        }];
        
        [alertController addAction:alertAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }


    NSLog(@"%@", self.result);
}

- (void)onError:(IFlySpeechError *)error
{
    NSLog(@"识别错误信息：%@", error);
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
